const Koa = require("koa");
const app = new Koa();

const json = require("koa-json");
const onerror = require("koa-onerror");
const bodyparser = require("koa-bodyparser");
const logger = require("koa-logger");
const error = require("koa-json-error");
const parameter = require("koa-parameter");
const mongoose = require("mongoose");

const config = require("./config");
const {formatError} = require("./utils")

mongoose.connect(
  config.mongodb,
  {
    useNewUrlParser: true,
  },
  () => console.log("mongodb 已连接"),
);
mongoose.connection.on("error", console.error);
 
const users = require("./routes/users");
const products = require("./routes/products");

// error handler
onerror(app);

// middlewares
app.use(
  bodyparser({
    enableTypes: ["json", "form", "text"],
  }),
);
app.use(json());
app.use(logger());
app.use(error(formatError));
app.use(parameter(app));

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
app.use(users.routes(), users.allowedMethods());
app.use(products.routes(), products.allowedMethods());

// error-handling
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});

app.listen(3101);
 
